<?php
/**
* 工厂模式
 * 返回业务逻辑类，从注册树获取底层框架类
 */

namespace myphp;


class Factory
{
    public static $proxy;
    // 获取数据库实例
    public static function getDb($type = "proxy")
    {
        // 代理数据库类: 实例化代理实现读写分离
        if($type == "proxy") {
            if(!self::$proxy) {
                self::$proxy = new \myphp\databases\Proxy();
            }
            return self::$proxy;
        }

        // 是否选择从库
        if($type == "slave") {
            // 读取配置从库参数
            $slaveConfig = Application::getInstance()->config['dbbases']['slave'];
            $dbConfig = $slaveConfig[array_rand($slaveConfig)];
        }else {     // 则为主库master
            // 读取配置文件主库参数
            $dbConfig = Application::getInstance()->config['dbbases'][$type];
        }

        $key = "databases".$type;
        $dbObj = Register::get($key);
        if(!$dbObj) {
            $dbType = '\myphp\databases\\'.ucwords($dbConfig['type']);
            $dbObj = new $dbType();
            Register::set($key,$dbObj);
        }
        $dbObj->connect($dbConfig['host'],$dbConfig['user'],$dbConfig['password'],$dbConfig['dbname']);

        return $dbObj;
    }


    // 获取对应模型类
    public static function getModel($name)
    {
        $key = "model".$name;
        // 获取注册树上的实例并判断是否存在
        $modelObj = Register::get($key);
        if(!$modelObj) {
            $className = '\\app\model\\'.ucwords($name);
            $modelObj = new $className();
            Register::set($key,$modelObj);
        }
        return $modelObj;
    }


    // 获取用户类型


}